<?php
class menu extends picMakeupEr {

    private $name = '菜单';

    public function __construct() {
        parent::__construct();
        $result = $this->Cache()->get( 'menu' );
        sort( $result );
        $this->result = $this->Node()->treeArray( $result );
    }

    public function index( $c, $a ) {
        include $this->display( $c );
    }

    public function add( $c, $a ) {
        include $this->display( $c );
    }

    public function edit( $c, $a ) {
        if ( !$id = intval( G( "id" ) ) ) {
            $this->error();
        }
        $this->table = $c;
        $result = $this->find( array( 'id' => $id ) );
        include $this->display( $c );
    }

    public function save( $c ) {
        foreach ( $_POST as $key => $val ) {
            $rows[ $key ] = htmlspecialchars( trim( $val ) );
        }

        $this->table = $c;
        if ( isset ( $rows[ 'id' ] ) && intval( $rows[ 'id' ] ) ) {
            $id = $rows[ 'id' ];
            unset( $rows[ 'id' ] );
            $msg = $this->update( array( 'id' => $id ), $rows ) ? 'success' : 'failed';
        } else {
            $msg = $this->create( $rows ) ? 'success' : 'failed';
        }

        $this->Cache()->update( $c );
        exit( $msg );
    }

    public function del( $c ) {
        if ( !$id = intval( G( "id" ) ) ) {
            addlog( 'system', $this->picMakeupEr[ 'author' ] . ": 非法删除菜单! " . getRequest( "REQUEST_URI" ) );
            exit( '非法删除菜单!' );
        }
        $this->table = $c;
        if ( $this->find( "sid = {$id}" ) ) {
            $msg = "该菜单下还有子菜单,请先删除子菜单!";
        } else {
            $msg = $this->delete( array( "id" => $id ) ) ? 'success' : 'failed';
            if ( $msg == 'success' ) {
                $this->Cache()->update( $c );
            }
        }
        exit( $msg );
    }

    public function oid( $c ) {
        $this->table = $c;
        foreach ( $_POST[ 'oid' ] as $k => $v ) {
            if ( !$return = $this->update( array( 'id' => $k ), array( 'oid' => $v ) ) ) {
                break;
            }
        }
        $this->Cache()->update( $c );
        $return = $return ? 'success' : 'failed';
        exit( $return );
    }
}